package cn.slipi.consumer.handler;

import cn.slipi.common.exception.BizException;
import cn.slipi.common.utils.JsonUtil;
import cn.slipi.consumer.facade.MessageCallFacade;
import cn.slipi.facade.api.message.form.MessageForm;
import cn.slipi.service.entity.TOrder;
import cn.slipi.service.service.TOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@RabbitListener(bindings = @QueueBinding(
        value = @Queue(value = "${order.queue}", autoDelete = "false"),
        exchange = @Exchange(value = "${mq.message.exchange}", type = ExchangeTypes.DIRECT),
        key = "${order.routing.key}"
))
public class OrderMessageHandler {

    private static final Logger logger = LoggerFactory.getLogger(OrderMessageHandler.class);


    @Autowired
    private TOrderService orderService;

    @Autowired
    private MessageCallFacade messageCallFacade;

    @Transactional(rollbackFor = BizException.class)
    @RabbitHandler
    public void process(String content) {
        logger.info("==========消息内容：{}：==========", content);
        MessageForm messageForm = JsonUtil.json2Object(content, MessageForm.class);
        //处理本地业务（修改订单为待发货）
        logger.info("==========修改订单为待发货==========");
        TOrder order = this.orderService.getOrderByNo(messageForm.getObjId());
        order.setState(1);
        this.orderService.getBaseMapper().updateById(order);
        //删除或完成消息
        this.messageCallFacade.completeMessage(messageForm.getObjId());
    }
}
